﻿#include "gamewindow.h"
#include "ui_gamewindow.h"
#include<QPainter>
#include<QBrush>

#define WIN_W   640
#define WIN_H   640
#define BLOCK_SIZE 16   //40x40 的格子
#define BLOCK_HALF 8

GameWindow::GameWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GameWindow)
{
    ui->setupUi(this);
    m_apple.x=0;
    m_apple.y=0;

    initData();
    m_gameTimer=new QTimer(this);
    connect(m_gameTimer,SIGNAL(timeout()),this,SLOT(onTimeOut()));

}

GameWindow::~GameWindow()
{
    delete ui;
}

void GameWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);

    //画网格
    for(int i=0;i<41;i++)
    {
        //画横线
        painter.drawLine(0,BLOCK_SIZE*i,WIN_W,BLOCK_SIZE*i);
        //画竖线
        painter.drawLine(BLOCK_SIZE*i,0,BLOCK_SIZE*i,WIN_H);
    }

    //画蛇
    for(int i=0;i<m_sanke.len;i++){
        QBrush bursh(Qt::green);
        if(i==0){ //画头

            painter.setBrush(bursh);
            painter.drawEllipse(m_sanke.points[i].x(),
                                m_sanke.points[i].y(),BLOCK_SIZE,BLOCK_SIZE);
            continue;
        }
        bursh.setColor(Qt::blue);
        painter.setBrush(bursh);
        painter.drawRect(m_sanke.points[i].x(),
                            m_sanke.points[i].y(),BLOCK_SIZE,BLOCK_SIZE);

    }
}

void GameWindow::initData()
{
    m_sanke.points[0].setX(20*BLOCK_SIZE);
    m_sanke.points[0].setY(20*BLOCK_SIZE);

    //蛇头除外
    for(int i=1;i<m_sanke.len;i++){
        m_sanke.points[i].setX(20*BLOCK_SIZE);
        m_sanke.points[i].setY(20*BLOCK_SIZE+i*BLOCK_SIZE);

    }
}

void GameWindow::onTimeOut()
{
    m_sanke.updatePos();
    update();
}

void GameWindow::startGame()
{
    m_gameTimer->start(500);
}
